#include <fs.h>
#include <types.h>
#include <kernel.h>
#include <string.h>

#define SECTOR_SIZE     512
#define OS_ADDR         0x100000
#define TEMP_ADDR       (8 * 1024 * 1024)
#define TEMP_FILE_ID    100

static uint8_t *temp_pos;

void read_disk(uint32_t sector, uint32_t count, uint16_t* buffer)
{
    outb(0x1F6, 0xE0);
    outb(0x1F2, (uint8_t)(count >> 8));
    outb(0x1F3, (uint8_t)(count >> 24));
    outb(0x1F4, 0);
    outb(0x1F5, 0);

    outb(0x1F2, (uint8_t)count);
    outb(0x1F3, (uint8_t)sector);
    outb(0x1F4, (uint8_t)(sector >> 8));
    outb(0x1F5, (uint8_t)(sector >> 16));

    outb(0x1F7, 0x24);

    uint16_t *ptr = buffer;
    while(count --) {
        while((inb(0x1F7) & 0x88) != 0x8) ;
        for (int i = 0; i < SECTOR_SIZE / 2; i++) {
            *ptr++ = inw(0x1F0);
        }
    }
}

int fs_sys_open(const char *name, int flags, ...)
{
    if (name[0] == '/') {
        read_disk(5000, 80, (uint16_t *)TEMP_ADDR);
        temp_pos = (uint8_t *)TEMP_ADDR;
        return TEMP_FILE_ID;
    }

    return -1;
}

int fs_sys_read(int file, char *ptr, int len)
{
    if (file == TEMP_FILE_ID) {
        kernel_memcpy(ptr, temp_pos, len);
        temp_pos += len;
        return len;
    }

    return -1;
}

int fs_sys_write(int file, char *ptr, int len)
{
    return -1;
}

int fs_sys_lseek(int file, int ptr, int dir)
{
    if (file == TEMP_FILE_ID) {
        temp_pos = (uint8_t *)(TEMP_ADDR + ptr);
        return 0;
    }

    return -1;
}

int fs_sys_close(int file)
{
    return 0;
}

int sys_fstat(int file, struct stat *st)
{

    return 0;
}

int sys_is_attry(int file)
{
    
    return 0;
}